package com.inderlab.jpin;

import java.lang.instrument.Instrumentation;
import java.lang.instrument.ClassFileTransformer;

import com.inderlab.jpin.JPFormer;
import com.inderlab.jpin.JPConfig;
import com.inderlab.jpin.JPCodeBook;

public class JPAgent
{
	static private Instrumentation inst = null;

	public static boolean  verbosemode   = false;
	public static boolean  compactmode   = false;
	public static boolean  sidemode   	 = false;
	public static boolean  matchmode     = false;
	public static boolean  depthmode     = false;

	static public  boolean  shutdown_hook = true;
	static private JPConfig config        = null;

	public static void premain(String agentArgs, Instrumentation _inst)
	{
		// Initialize the static variables we use to track information.
		inst = _inst;

		// Resiter shutdown hook for saving CodeBook to the local disk
		if(shutdown_hook)
		{
			shutdown_hook = false;
			Runtime.getRuntime().addShutdownHook(new Thread() {
			    public void run() {
					System.out.println((sidemode ? JPColor.MARGIN:"")+"[jpin] Saving CodeBook....");
					JPCodeBook.writeCodeBook(); 
					System.out.println((sidemode ? JPColor.MARGIN:"")+"[jpin] Saving CodeBook....DONE");
				}
			});	
		}

		// Check args for config file and mode
		if(agentArgs != null)
		{
			try {
				String[] args = agentArgs.split(",");				
				String[] mode = args[1].split("=");

				if(mode[0].equals("mode"))
				{
					if(mode[1].contains("v"))
						verbosemode = true;
					if(mode[1].contains("c"))
						compactmode = true;					
					if(mode[1].contains("l"))
						compactmode = false;					
					if(mode[1].contains("s"))
						sidemode = true;					
					if(mode[1].contains("m"))
						matchmode = true;					
					if(mode[1].contains("d"))
						depthmode = true;
				}

				config = new JPConfig(args[0]);
						
			} catch(Exception e)
			{
				System.out.println("Error: Syntax Error"+e);
				config  = new JPConfig("./jpin.conf");
				compactmode = true;
			}
		}
		else
		{
			config  = new JPConfig("./jpin.conf");
			compactmode = true;			
			verbosemode = true;			
		}
		
		if(verbosemode)
		{
			System.out.println((sidemode ? JPColor.MARGIN:"")+JPColor.C2+"[jpin] *START*"+JPColor.RESET);
			System.out.println((sidemode ? JPColor.MARGIN:"")+JPColor.C2+"[jpin] Args=["+agentArgs+"]");
			System.out.println((sidemode ? JPColor.MARGIN:"")+JPColor.C2+"[jpin] nomde=["+compactmode+"]");			
		}
					
		ClassFileTransformer trans = new JPFormer();
		((JPFormer)trans).setConfig(config);
		
		if(verbosemode)
		{
			System.out.println((sidemode ? JPColor.MARGIN:"")+JPColor.C2+"[jpin] *addTransdormer*"+JPColor.RESET);			
		}
			
		inst.addTransformer(trans);
	}
}
